//
//  Concept_DispatchQueue_DemoVC.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/10/22.
//

import UIKit

class Concept_DispatchQueue_DemoVC: UIViewController {
    private var money: Int = 10000

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
//        asyncSaveDrawMoney()
        syncSaveDrawMoney()
    }

}

//!!!: 「异步（普通）」存、取钱示例
extension Concept_DispatchQueue_DemoVC {
    func asyncSaveDrawMoney() {
        let queue = DispatchQueue(label: "ap.swift.save.draw.money.queue", attributes: .concurrent)
        queue.async { [weak self] in
            for _ in 0..<5 {
                self?.saveMoney()
            }
        }
        
        queue.async { [weak self] in
            for _ in 0..<5 {
                self?.drawMoney()
            }
        }
    
    }
    
    func saveMoney() {
        sleep(2)
        money += 200
        print("存钱 - money is \(money), \(Thread.current)")
    }
    
    func drawMoney() {
        sleep(2)
        money -= 10
        print("取钱 - money is \(money), \(Thread.current)")
    }
    
    func syncSaveDrawMoney() {
        for _ in 0..<5 {
            saveMoney()
        }
        for _ in 0..<5 {
            drawMoney()
        }
    }
    
}
